package com.mdp.arc.archive.ctrl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.arc.archive.entity.Archive;
import com.mdp.arc.archive.entity.ArchiveComment;
import com.mdp.arc.archive.service.ArchiveCalcService;
import com.mdp.arc.archive.service.ArchiveCommentService;
import com.mdp.arc.archive.service.ArchiveService;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.msg.client.PushNotifyMsgService;
import com.mdp.qx.HasRole;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

/**
 * url编制采用rest风格,如对ARC.arc_archive_comment 档案评论表的操作有增删改查,对应的url分别为:<br>
 *  新增: arc/archiveComment/add <br>
 *  查询: arc/archiveComment/list<br>
 *  模糊查询: arc/archiveComment/listKey<br>
 *  修改: arc/archiveComment/edit <br>
 *  删除: arc/archiveComment/del<br>
 *  批量删除: arc/archiveComment/batchDel<br>
 * 组织 com.qqkj  顶级模块 mdp 大模块 arc 小模块 <br>
 * 实体 ArchiveComment 表 ARC.arc_archive_comment 当前主键(包括多主键): id; 
 ***/
@RestController("mdp.arc.archiveCommentController")
@RequestMapping(value="/*/arc/archive/archiveComment")
@Api(tags={"档案评论表操作接口"})
public class ArchiveCommentController {
	
	static Log logger=LogFactory.getLog(ArchiveCommentController.class);
	
	@Autowired
	private ArchiveCommentService archiveCommentService;

	@Autowired
	PushNotifyMsgService pushNotifyMsgService;

	@Autowired
	private ArchiveService archiveService;
	
	@ApiOperation( value = "查询档案评论表信息列表",notes="listArchiveComment,条件之间是 and关系,模糊查询写法如 {studentName:'%才哥%'}")
 	@ApiEntityParams(ArchiveComment.class)
	@ApiResponses({
		@ApiResponse(code = 200,response= ArchiveComment.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listArchiveComment(@ApiIgnore @RequestParam Map<String,Object> params ){
		
		List<Map<String,Object>>	archiveCommentList= null;
		List<Map<String,Object>>	archiveCommentListMap= null;
		IPage page= QueryTools.initPage(params);

		if("true".equals((String)params.get("noPcomment"))){
			archiveCommentListMap = archiveCommentService.selectCommentListNoPcomment(page,params);
			return Result.ok().setData(archiveCommentListMap);
		}else{
			archiveCommentList = archiveCommentService.selectListMapByWhere(page,QueryTools.initQueryWrapper(ArchiveComment.class,params), params );//列出ArchiveComment列表
			return Result.ok().setData(archiveCommentList);
		}
	}

	@ApiEntityParams(ArchiveComment.class)
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveComment.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/commentListLevel",method=RequestMethod.GET)
	public Result listArchiveCommentLevel(@ApiIgnore @RequestParam Map<String,Object> params ){
		
		String pcommentId= (String) params.get("pcommentId");
		if(!StringUtils.hasText(pcommentId)){
			params.put("pcommentIdIsNull","1");
		}
		Result result= Result.ok();
		IPage page= QueryTools.initPage(params);
		List<Map<String,Object>> archives=archiveCommentService.selectListMapByWhere( page,QueryTools.initQueryWrapper(ArchiveComment.class,params),params );
		if(archives.size()>0) {
		 List<Map<String, Object>> archiveLevel=archiveCommentService.selectArchiveCommentLev(archives.stream().map(k->(String)k.get("id")).collect(Collectors.toList()));
			result.put("children",archiveLevel);
		}
		return result.setData( archives);
	}
	@ApiOperation( value = "新增一条档案评论表信息",notes="addArchiveComment,主键如果为空，后台自动生成")
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveComment.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	})
	@HasRole
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Result addArchiveComment(@RequestBody ArchiveComment archiveComment) {
		
		
		try{
			User user=LoginUtils.getCurrentUserInfo();
			Archive archiveDb=this.archiveService.selectOneById(archiveComment.getArchiveId());
			if(archiveDb==null){
				return Result.error("archive-0","文章已不存在");
			}
			if(!"1".equals(archiveDb.getCanComment())){
				return Result.error("open-comment-0","文章已关闭评论");
			}
			archiveComment.setId(archiveCommentService.createKey("id"));
			archiveComment.setBranchId(user.getBranchId());
			archiveComment.setUserid(user.getUserid());
			archiveComment.setUsername(user.getUsername());
			archiveComment.setCreateDate(new Date());
			archiveComment.setIp(RequestUtils.getIpAddr(RequestUtils.getRequest()));
			archiveCommentService.insert(archiveComment);
			if(StringUtils.hasText(archiveComment.getPcommentId())){
				archiveCommentService.updateChildrenSum(archiveComment.getPcommentId(),Integer.valueOf(1));
			}
			ArchiveCalcService.commentsSet.add(archiveComment.getArchiveId());
			if(!user.getUserid().equals(archiveDb.getUserid())){
				pushNotifyMsgService.pushMsg(user, archiveDb.getUserid(), archiveDb.getAuthorName(),user.getUsername()+"发表评论："+archiveComment.getContext(),null);
			}
			return Result.ok().setData(archiveComment);
		}catch (BizException e) { 
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}
	

	@ApiOperation( value = "删除一条档案评论表信息",notes="delArchiveComment,仅需要上传主键字段")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")
	}) 
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delArchiveComment(@RequestBody ArchiveComment archiveComment){
		
		
		try{
			ArchiveComment commentDb=this.archiveCommentService.selectOneById(archiveComment.getId());
			if(commentDb==null){
				return Result.error("data-0","评论已不存在");
			}
			User user=LoginUtils.getCurrentUserInfo();
			if(!LoginUtils.isSuperAdmin()){
				if(!LoginUtils.isBranchAdmin(commentDb.getBranchId())){
					if(!user.getUserid().equals(commentDb.getUserid())){
						return Result.error("no-qx-0","无权限删除评论");
					}
				}
			}
			archiveCommentService.deleteByPk(archiveComment);
			if(StringUtils.hasText(commentDb.getPcommentId())){
				archiveCommentService.updateChildrenSum(commentDb.getPcommentId(),Integer.valueOf(-1));
			}
		}catch (BizException e) { 
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}  
		return Result.ok();
	}

	
	@ApiOperation( value = "点赞评论",notes="praiseComment")
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveComment.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/praise",method=RequestMethod.POST)
	public Result praiseComment(@RequestBody ArchiveComment archiveComment) {
		
		
		try{
			archiveCommentService.praiseComment(archiveComment);

			return Result.ok().setData(archiveComment);
		}catch (BizException e) { 
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}
	
	@ApiOperation( value = "屏蔽评论",notes="unShowComment")
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveComment.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/unshow",method=RequestMethod.POST)
	public Result unShowComment(@RequestBody String[] ids) {
		
		
		try{
			User user=LoginUtils.getCurrentUserInfo();
			List<ArchiveComment> comments=this.archiveCommentService.selectListByIds(Arrays.asList(ids));
			if(comments==null || comments.size()==0){
				return Result.error("data-0","评论已不存在");
			}
			boolean isSuperAdmin=LoginUtils.isSuperAdmin();
			for (ArchiveComment comment : comments) {
				if(!isSuperAdmin){
					if(!LoginUtils.isBranchAdmin(comment.getBranchId())){
						if(!user.getUserid().equals(comment.getUserid())){
							return Result.error("无权限修改","无权限屏蔽评论【"+comment.getContext()+"】");
						}
					}
				}
			}
			archiveCommentService.unShowComment(ids); 
		}catch (BizException e) { 
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}  
		return Result.ok();
	}
	
	@ApiOperation( value = "打开评论",notes="showComment")
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveComment.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/show",method=RequestMethod.POST)
	public Result showComment(@RequestBody String[] ids) {
		
		
		try{
			User user=LoginUtils.getCurrentUserInfo();
			List<ArchiveComment> comments=this.archiveCommentService.selectListByIds(Arrays.asList(ids));
			if(comments==null || comments.size()==0){
				return Result.error("data-0","评论已不存在");
			}
			boolean isSuperAdmin=LoginUtils.isSuperAdmin();
			for (ArchiveComment comment : comments) {
				if(!isSuperAdmin){
					if(!LoginUtils.isBranchAdmin(comment.getBranchId())){
						if(!user.getUserid().equals(comment.getUserid())){
							return Result.error("无权限修改","无权限打开此评论【"+comment.getContext()+"】");
						}
					}
				}
			}
			archiveCommentService.showComment(ids); 
		}catch (BizException e) { 
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}  
		return Result.ok();
	}

	@ApiOperation( value = "根据主键列表批量删除档案评论表信息",notes="batchDelArchiveComment,仅需要上传主键字段")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")
	}) 
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelArchiveComment(@RequestBody List<ArchiveComment> archiveComments) {
		
		
		try{
			User user=LoginUtils.getCurrentUserInfo();
			List<ArchiveComment> comments=this.archiveCommentService.selectListByIds(archiveComments.stream().map(i->i.getId()).collect(Collectors.toList()));
			if(comments==null || comments.size()==0){
				return Result.error("data-0","评论已不存在");
			}
			boolean isSuperAdmin=LoginUtils.isSuperAdmin();
			for (ArchiveComment comment : comments) {
				if(!isSuperAdmin){
					if(!LoginUtils.isBranchAdmin(comment.getBranchId())){
						if(!user.getUserid().equals(comment.getUserid())){
							return Result.error("无权限修改","无权限删除此评论【"+comment.getContext()+"】");
						}
					}
				}
			}
			archiveCommentService.batchDelete(archiveComments);
			Map<String,Integer> data=new HashMap<>();
			for (ArchiveComment comment : comments) {
				if(StringUtils.hasText(comment.getPcommentId())){
					Integer i=data.get(comment.getPcommentId());
					if(i==null){
						i=new Integer("0");
						data.put(comment.getPcommentId(),i-1);
					}else{
						data.put(comment.getPcommentId(),i-1);
					}
				}
			}
			if(!data.isEmpty()){
				for (Map.Entry<String, Integer> entry : data.entrySet()) {
					archiveCommentService.updateChildrenSum(entry.getKey(),entry.getValue());
				}
			}

		}catch (BizException e) { 
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}  
		return Result.ok();
	}
}
